// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('userManager云函数接收到的事件:', event)
  
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext
  
  try {
    const { action } = event
    
    // 首先检查当前用户是否为管理员
    const currentUserResult = await db.collection('users').where({
      openId: OPENID
    }).get()
    
    if (currentUserResult.data.length === 0 || !currentUserResult.data[0].isAdmin) {
      return {
        success: false,
        message: '权限不足，仅管理员可以进行此操作'
      }
    }
    
    if (action === 'getAllUsers') {
      // 获取所有用户列表
      const usersResult = await db.collection('users')
        .orderBy('createTime', 'desc')
        .get()
      
      const users = usersResult.data.map(user => ({
        _id: user._id,
        openId: user.openId,
        nickName: user.nickName || '未设置昵称',
        avatarUrl: user.avatarUrl || '',
        isAdmin: user.isAdmin || false,
        createTime: user.createTime,
        lastLoginTime: user.lastLoginTime
      }))
      
      console.log('获取所有用户列表成功，共', users.length, '个用户')
      
      return {
        success: true,
        message: '获取用户列表成功',
        data: {
          users: users,
          total: users.length
        }
      }
    } else if (action === 'updateUserAdmin') {
      // 更新用户管理员权限
      const { targetOpenId, isAdmin } = event
      
      if (!targetOpenId) {
        return {
          success: false,
          message: '缺少目标用户openId参数'
        }
      }
      
      // 检查目标用户是否存在
      const targetUserResult = await db.collection('users').where({
        openId: targetOpenId
      }).get()
      
      if (targetUserResult.data.length === 0) {
        return {
          success: false,
          message: '目标用户不存在'
        }
      }
      
      // 防止用户取消自己的管理员权限
      if (targetOpenId === OPENID && !isAdmin) {
        return {
          success: false,
          message: '不能取消自己的管理员权限'
        }
      }
      
      // 更新用户的管理员权限
      await db.collection('users').where({
        openId: targetOpenId
      }).update({
        data: {
          isAdmin: isAdmin
        }
      })
      
      const targetUser = targetUserResult.data[0]
      const operationText = isAdmin ? '设置为管理员' : '取消管理员权限'
      
      console.log(`用户权限更新成功: ${targetUser.nickName}(${targetOpenId}) ${operationText}`)
      
      return {
        success: true,
        message: `已${operationText}`,
        data: {
          targetOpenId: targetOpenId,
          targetNickName: targetUser.nickName,
          isAdmin: isAdmin
        }
      }
    } else if (action === 'getUserDetail') {
      // 获取用户详情
      const { targetOpenId } = event
      
      if (!targetOpenId) {
        return {
          success: false,
          message: '缺少目标用户openId参数'
        }
      }
      
      const userResult = await db.collection('users').where({
        openId: targetOpenId
      }).get()
      
      if (userResult.data.length === 0) {
        return {
          success: false,
          message: '用户不存在'
        }
      }
      
      const user = userResult.data[0]
      
      // 获取用户的投票记录统计
      const voteResult = await db.collection('votes').where({
        _openid: targetOpenId
      }).count()
      
      const userDetail = {
        _id: user._id,
        openId: user.openId,
        nickName: user.nickName || '未设置昵称',
        avatarUrl: user.avatarUrl || '',
        isAdmin: user.isAdmin || false,
        createTime: user.createTime,
        lastLoginTime: user.lastLoginTime,
        voteCount: voteResult.total
      }
      
      return {
        success: true,
        message: '获取用户详情成功',
        data: userDetail
      }
    } else {
      return {
        success: false,
        message: '未知操作类型'
      }
    }
  } catch (error) {
    console.error('userManager云函数执行失败:', error)
    return {
      success: false,
      message: '操作失败，请重试',
      error: error.message
    }
  }
} 